<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="45%"
      v-dialogDrag
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        v-loading="formLoading"
        label-width="100px"
      >
        <el-form-item label="父级ID" prop="pid">
          <TreeSelect
            v-model="formData.pid"
            :options="categoryTree"
            :normalizer="normalizer"
            placeholder="请选择父级ID"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="分类图标">
          <ImageUpload v-model="formData.extra" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in searchOption"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="10" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCheck" :disabled="formLoading"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as CategoryApi from "@/api/store/category";
import ImageUpload from "@/components/ImageUpload";
import TreeSelect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "CategoryForm",
  components: {
    ImageUpload,
    TreeSelect,
  },
  data() {
    return {
      queryParams: {
        id: null,
        name: null,
        status: 1,
      },
      searchOption: [
        { value: 1, label: "显示" },
        { value: 0, label: "不显示" },
      ],
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: null,
        pid: null,
        name: null,
        extra: null,
        status: null,
        sort: null,
      },
      // 表单校验
      formRules: {
        pid: [{ required: true, message: "父级ID不能为空", trigger: "blur" }],
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
      },
      categoryTree: [], // 树形结构
      categoryChildren: null,
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(row) {
      this.reset();
      this.dialogVisible = true;
      // 修改时，设置数据
      if (row && row.id) {
        this.formLoading = true;
        try {
          this.categoryChildren = row;
          this.queryParams.id = row.id;
          const res = await CategoryApi.getCategory(row.id);
          this.formData = res.data;
          
          // 处理 extra 字段：如果是字符串，转换为数组供 ImageUpload 组件使用
          if (typeof this.formData.extra === 'string' && this.formData.extra) {
            this.formData.extra = this.formData.extra.split(',').filter(item => item.trim());
          }
          
          this.title = "修改商品分类";
        } finally {
          this.formLoading = false;
        }
      }
      this.title = "新增商品分类";
      await this.getCategoryTree();
    },
    // 表单验证
    submitCheck() {
      this.$refs["formRef"].validate((valid) => {
        if (valid) {
          this.submitForm();
        }
      });
    },
    /** 提交按钮 */
    async submitForm() {
      try {
        this.formLoading = true;
        const data = { ...this.formData };
        
        // 处理 extra 字段：如果是数组，转换为字符串
        if (Array.isArray(data.extra)) {
          data.extra = data.extra.join(',');
        }
        
        // 修改的提交
        if (data.id) {
          await CategoryApi.updateCategory(data).then(() => {
            if (
              this.categoryChildren.children &&
              this.categoryChildren.children.length > 0 &&
              this.formData.status != this.categoryChildren.status
            ) {
              this.categoryChildren.status = this.formData.status;
              // 触发事件通知父组件更新
              this.$emit("updateCategorys", this.categoryChildren);
            }
            this.$message.success("修改成功");
          });
        }
        // 添加的提交
        else {
          await CategoryApi.createCategory(data).then(() => {
            this.$message.success("新增成功");
          });
        }

        // 操作成功，关闭对话框并通知父组件
        this.dialogVisible = false;
        this.$emit("success");
      } catch (error) {
        // 错误处理
        console.error("表单提交失败:", error);
      } finally {
        this.formLoading = false;
      }
    },
    /** 获得商品分类树 */
    async getCategoryTree() {
      this.categoryTree = [];
      const res = await CategoryApi.getCategoryList(this.queryParams);
      const root = { id: 0, name: "顶级商品分类", children: [] };
      root.children = this.handleTree(res.data, "id", "pid");
      this.categoryTree.push(root);
    },
    /** 转换商品分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    /** 表单重置 */
    reset() {
      this.queryParams.id = null;
      this.categoryChildren = null;
      this.formData = {
        pid: null,
        name: null,
        extra: null,
        status: 1,
        sort: null,
      };
      this.resetForm("formRef");
    },
  },
};
</script>
